home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Math / BigFloat.pm next >
Encoding:
Perl POD Document  |  1999-12-28  |  7.8 KB  |  304 lines

  1. package Math::BigFloat;
  2.  
  3. use Math::BigInt;
  4.  
  5. use Exporter;  # just for use to be happy
  6. @ISA = (Exporter);
  7.  
  8. use overload
  9. '+'    =>    sub {new Math::BigFloat &fadd},
  10. '-'    =>    sub {new Math::BigFloat
  11.                $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
  12. '<=>'    =>    sub {new Math::BigFloat
  13.                $_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
  14. 'cmp'    =>    sub {new Math::BigFloat
  15.                $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
  16. '*'    =>    sub {new Math::BigFloat &fmul},
  17. '/'    =>    sub {new Math::BigFloat 
  18.                $_[2]? scalar fdiv($_[1],${$_[0]}) :
  19.              scalar fdiv(${$_[0]},$_[1])},
  20. 'neg'    =>    sub {new Math::BigFloat &fneg},
  21. 'abs'    =>    sub {new Math::BigFloat &fabs},
  22.  
  23. qw(
  24. ""    stringify
  25. 0+    numify)            # Order of arguments unsignificant
  26. ;
  27.  
  28. sub new {
  29.   my ($class) = shift;
  30.   my ($foo) = fnorm(shift);
  31.   panic("Not a number initialized to Math::BigFloat") if $foo eq "NaN";
  32.   bless \$foo, $class;
  33. }
  34. sub numify { 0 + "${$_[0]}" }    # Not needed, additional overhead
  35. sub stringify {
  36.     my $n = ${$_[0]};
  37.  
  38.     $n =~ s/^\+//;
  39.     $n =~ s/E//;
  40.  
  41.     $n =~ s/([-+]\d+)$//;
  42.  
  43.     my $e = $1;
  44.     my $ln = length($n);
  45.  
  46.     if ($e > 0) {
  47.     $n .= "0" x $e . '.';
  48.     } elsif (abs($e) < $ln) {
  49.     substr($n, $ln + $e, 0) = '.';
  50.     } else {
  51.     $n = '.' . ("0" x (abs($e) - $ln)) . $n;
  52.     }
  53.  
  54.  
  55.     return $n;
  56. }
  57.  
  58. $div_scale = 40;
  59.  
  60.  
  61. $rnd_mode = 'even';
  62.  
  63. sub fadd; sub fsub; sub fmul; sub fdiv;
  64. sub fneg; sub fabs; sub fcmp;
  65. sub fround; sub ffround;
  66. sub fnorm; sub fsqrt;
  67.  
  68. sub fnorm { #(string) return fnum_str
  69.     local($_) = @_;
  70.     s/\s+//g;                               # strip white space
  71.     if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
  72.     &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
  73.     } else {
  74.     'NaN';
  75.     }
  76. }
  77.  
  78. sub norm { #(mantissa, exponent) return fnum_str
  79.     local($_, $exp) = @_;
  80.     if ($_ eq 'NaN') {
  81.     'NaN';
  82.     } else {
  83.     s/^([+-])0+/$1/;                        # strip leading zeros
  84.     if (length($_) == 1) {
  85.         '+0E+0';
  86.     } else {
  87.         $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
  88.         sprintf("%sE%+ld", $_, $exp);
  89.     }
  90.     }
  91. }
  92.  
  93. sub fneg { #(fnum_str) return fnum_str
  94.     local($_) = fnorm($_[$[]);
  95.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
  96.     s/^H/N/;
  97.     $_;
  98. }
  99.  
  100. sub fabs { #(fnum_str) return fnum_str
  101.     local($_) = fnorm($_[$[]);
  102.     s/^-/+/;                               # mash sign
  103.     $_;
  104. }
  105.  
  106. sub fmul { #(fnum_str, fnum_str) return fnum_str
  107.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  108.     if ($x eq 'NaN' || $y eq 'NaN') {
  109.     'NaN';
  110.     } else {
  111.     local($xm,$xe) = split('E',$x);
  112.     local($ym,$ye) = split('E',$y);
  113.     &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
  114.     }
  115. }
  116.  
  117. sub fadd { #(fnum_str, fnum_str) return fnum_str
  118.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  119.     if ($x eq 'NaN' || $y eq 'NaN') {
  120.     'NaN';
  121.     } else {
  122.     local($xm,$xe) = split('E',$x);
  123.     local($ym,$ye) = split('E',$y);
  124.     ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
  125.     &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
  126.     }
  127. }
  128.  
  129. sub fsub { #(fnum_str, fnum_str) return fnum_str
  130.     fadd($_[$[],fneg($_[$[+1]));    
  131. }
  132.  
  133. sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
  134. {
  135.     local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
  136.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
  137.     'NaN';
  138.     } else {
  139.     local($xm,$xe) = split('E',$x);
  140.     local($ym,$ye) = split('E',$y);
  141.     $scale = $div_scale if (!$scale);
  142.     $scale = length($xm)-1 if (length($xm)-1 > $scale);
  143.     $scale = length($ym)-1 if (length($ym)-1 > $scale);
  144.     $scale = $scale + length($ym) - length($xm);
  145.     &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym),
  146.         $xe-$ye-$scale);
  147.     }
  148. }
  149.  
  150. sub round { #(int_str, int_str, int_str) return int_str
  151.     local($q,$r,$base) = @_;
  152.     if ($q eq 'NaN' || $r eq 'NaN') {
  153.     'NaN';
  154.     } elsif ($rnd_mode eq 'trunc') {
  155.     $q;                         # just truncate
  156.     } else {
  157.     local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
  158.     if ( $cmp < 0 ||
  159.          ($cmp == 0 &&
  160.           ( $rnd_mode eq 'zero'                             ||
  161.            ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
  162.            ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
  163.            ($rnd_mode eq 'even' && $q =~ /[24680]$/)        ||
  164.            ($rnd_mode eq 'odd'  && $q =~ /[13579]$/)        )) ) {
  165.         $q;                     # round down
  166.     } else {
  167.         Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
  168.     }
  169.     }
  170. }
  171.  
  172. sub fround { #(fnum_str, scale) return fnum_str
  173.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  174.     if ($x eq 'NaN' || $scale <= 0) {
  175.     $x;
  176.     } else {
  177.     local($xm,$xe) = split('E',$x);
  178.     if (length($xm)-1 <= $scale) {
  179.         $x;
  180.     } else {
  181.         &norm(&round(substr($xm,$[,$scale+1),
  182.              "+0".substr($xm,$[+$scale+1,1),"+10"),
  183.           $xe+length($xm)-$scale-1);
  184.     }
  185.     }
  186. }
  187.  
  188. sub ffround { #(fnum_str, scale) return fnum_str
  189.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  190.     if ($x eq 'NaN') {
  191.     'NaN';
  192.     } else {
  193.     local($xm,$xe) = split('E',$x);
  194.     if ($xe >= $scale) {
  195.         $x;
  196.     } else {
  197.         $xe = length($xm)+$xe-$scale;
  198.         if ($xe < 1) {
  199.         '+0E+0';
  200.         } elsif ($xe == 1) {
  201.         &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
  202.         } else {
  203.         &norm(&round(substr($xm,$[,$xe),
  204.               "+0".substr($xm,$[+$xe,1),"+10"), $scale);
  205.         }
  206.     }
  207.     }
  208. }
  209.     
  210. sub fcmp #(fnum_str, fnum_str) return cond_code
  211. {
  212.     local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  213.     if ($x eq "NaN" || $y eq "NaN") {
  214.     undef;
  215.     } else {
  216.     ord($y) <=> ord($x)
  217.     ||
  218.     (  local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
  219.          (($xe <=> $ye) * (substr($x,$[,1).'1')
  220.              || Math::BigInt::cmp($xm,$ym))
  221.     );
  222.     }
  223. }
  224.  
  225. sub fsqrt { #(fnum_str[, scale]) return fnum_str
  226.     local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
  227.     if ($x eq 'NaN' || $x =~ /^-/) {
  228.     'NaN';
  229.     } elsif ($x eq '+0E+0') {
  230.     '+0E+0';
  231.     } else {
  232.     local($xm, $xe) = split('E',$x);
  233.     $scale = $div_scale if (!$scale);
  234.     $scale = length($xm)-1 if ($scale < length($xm)-1);
  235.     local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
  236.     while ($gs < 2*$scale) {
  237.         $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
  238.         $gs *= 2;
  239.     }
  240.     new Math::BigFloat &fround($guess, $scale);
  241.     }
  242. }
  243.  
  244. 1;
  245. __END__
  246.  
  247. =head1 NAME
  248.  
  249. Math::BigFloat - Arbitrary length float math package
  250.  
  251. =head1 SYNOPSIS
  252.  
  253.   use Math::BogFloat;
  254.   $f = Math::BigFloat->new($string);
  255.  
  256.   $f->fadd(NSTR) return NSTR            addition
  257.   $f->fsub(NSTR) return NSTR            subtraction
  258.   $f->fmul(NSTR) return NSTR            multiplication
  259.   $f->fdiv(NSTR[,SCALE]) returns NSTR   division to SCALE places
  260.   $f->fneg() return NSTR                negation
  261.   $f->fabs() return NSTR                absolute value
  262.   $f->fcmp(NSTR) return CODE            compare undef,<0,=0,>0
  263.   $f->fround(SCALE) return NSTR         round to SCALE digits
  264.   $f->ffround(SCALE) return NSTR        round at SCALEth place
  265.   $f->fnorm() return (NSTR)             normalize
  266.   $f->fsqrt([SCALE]) return NSTR        sqrt to SCALE places
  267.  
  268. =head1 DESCRIPTION
  269.  
  270. All basic math operations are overloaded if you declare your big
  271. floats as
  272.  
  273.     $float = new Math::BigFloat "2.123123123123123123123123123123123";
  274.  
  275. =over 2
  276.  
  277. =item number format
  278.  
  279. canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
  280. have inbedded whitespace.
  281.  
  282. =item Error returns 'NaN'
  283.  
  284. An input parameter was "Not a Number" or divide by zero or sqrt of
  285. negative number.
  286.  
  287. =item Division is computed to 
  288.  
  289. C<max($div_scale,length(dividend)+length(divisor))> digits by default.
  290. Also used for default sqrt scale.
  291.  
  292. =back
  293.  
  294. =head1 BUGS
  295.  
  296. The current version of this module is a preliminary version of the
  297. real thing that is currently (as of perl5.002) under development.
  298.  
  299. =head1 AUTHOR
  300.  
  301. Mark Biggar
  302.  
  303. =cut
  304.